Attachments

Download a File from the File System

Description
This customization shows how to download a file from the file system.
Variables
Download Button Control
Select the download button
Applies to
P_Download Button Control class
Code
 
/// 
/// event handler for Button that downloads 
/// myfile.txt from a subfolder called Data in the current directory
///  
public override void ${Download Button Control}_Click( Object sender, EventArgs args)
{
    string fileName = "myfile.txt";
    bool fileExists = System.IO.File.Exists((this.Page.Server.MapPath("..\\Data") + ("\\" + fileName)));
    if (fileExists)
    {
        // Set up file stream object.
        System.IO.FileStream fs;
        fs = new System.IO.FileStream((this.Page.Server.MapPath("..\\Data") + ("\\" + fileName)), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
        string fullFileName = (this.Page.Server.MapPath("..\\Data") + ("\\" + fileName));
        try
        {
            // Read the contents of the file.
            int bufSize = ((int)(fs.Length));
            byte[] buf = new byte[bufSize];
            int bytesRead = fs.Read(buf, 0, bufSize);
            
            // Set up parameters for file download.
            this.Page.Response.ContentType = "application/octet-stream";
            this.Page.Response.AppendHeader("Content-Disposition", ("attachment;filename=" + fileName));
            
            // Download the file.
            this.Page.Response.OutputStream.Write(buf, 0, bytesRead);
            this.Page.Response.Flush();
        }
        catch (Exception ex)
        {
            // Report the error message to the user
            BaseClasses.Utils.MiscUtils.RegisterJScriptAlert(this, "UNIQUE_SCRIPTKEY", ex.Message);
        }
        finally
        {
            fs.Close();
        }
    }
    else
    {
        this.Page.Response.Write("File cannot be found to download");
    }
}

 

Terms of Service Privacy Statement